<template>
  <div>{{ num }}</div>
  <button @click="changeNum">changeNum</button>

  <div>{{ person.name }}</div>
  <button @click="changeName">changeName</button>
  <button @click="changePerson">changePerson</button>
  <button @click="changeCar">changeCar</button>

  <div>监听2个属性</div>
  <div>温度：{{ water.temp }}℃ <button @click="changeTemp">+</button></div>
  <div>水位：{{ water.height }}cm <button @click="changeHeight">+</button></div>

  <div>watchEffect</div>
  <div>width：{{ block.width }} <button @click="changeW">+</button></div>
  <div>height：{{ block.height }} <button @click="changeH">+</button></div>
  <div>面积：{{ block.area }}</div>
</template>

<script lang="ts" setup>
import { ref, watch, watchEffect } from 'vue';

// 监听基础数据
let num = ref(0)
function changeNum() {
  num.value += 1
}
let stopWatch = watch(num, (newVal, oldVal) => {
  console.log(newVal, oldVal)
  if (newVal >= 10) {
    stopWatch()
  }
})

// 监听对象数据
let person = ref({ name: '张三', age: 18, car: { c1: "本田", c2: "路虎" } })
function changeName() {
  person.value.name += '~'
}
function changePerson() {
  person.value = { name: '李四', age: 20, car: { c1: "本田", c2: "路虎"  } }
}
watch(person, (newVal, oldVal) => {  // 只修改属性时，因为对象地址没变，因为newVal与oldVal是使用同一个引用，所以2个对象完全相同
  console.log(newVal, oldVal)
}, {deep: true, immediate: true})

// 监听对象的属性
function changeCar() {
  person.value.car = { c1: "马自达", c2: "奔驰" }
}
watch(() => person.value.car, (newVal, oldVal) => {
  console.log(newVal, oldVal)
}, { deep: true })

// 监听2个属性
let water = ref({ temp: 80, height: 0 })
function changeTemp() { water.value.temp += 10 }
function changeHeight() { water.value.height += 10 }
watch([() => water.value.temp, () => water.value.height], (newVal, oldVal) => {
  console.log(newVal, oldVal)
}, { deep: true })

// 立即执行函数watchEffect，在依赖变化时，自动执行函数。
let block = ref({ width: 50, height: 50, area: 0 })
function changeW() { block.value.width += 10 }
function changeH() { block.value.height += 10 }
watchEffect(() => {
  block.value.area = block.value.width * block.value.height
})
</script>

<style lang="scss" scoped>

</style>
